package com.apimanage.common.controller;

import com.apimanage.common.health.HealthCheckManager;
import com.apimanage.common.health.HealthCheckResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 健康检查控制器
 * 提供HTTP接口用于查看系统健康状态
 *
 * @author API管理平台
 */
@RestController
@RequestMapping("/api/health")
public class HealthCheckController {
    
    private static final Logger logger = LoggerFactory.getLogger(HealthCheckController.class);
    
    @Autowired
    private HealthCheckManager healthCheckManager;
    
    /**
     * 获取系统健康状态概览
     * @return 健康状态概览
     */
    @GetMapping("/status")
    public Map<String, Object> getHealthStatus() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<HealthCheckResult> results = healthCheckManager.getLastCheckResults();
            boolean allHealthy = results.stream().allMatch(HealthCheckResult::isHealthy);
            
            response.put("status", allHealthy ? "UP" : "DOWN");
            response.put("timestamp", System.currentTimeMillis());
            response.put("components", results.size());
            response.put("healthyComponents", results.stream().filter(HealthCheckResult::isHealthy).count());
            
            logger.info("获取系统健康状态: {}", response.get("status"));
        } catch (Exception e) {
            logger.error("获取系统健康状态时发生异常", e);
            response.put("status", "UNKNOWN");
            response.put("error", e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 获取详细的健康检查结果
     * @return 详细的健康检查结果
     */
    @GetMapping("/details")
    public Map<String, Object> getHealthDetails() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<HealthCheckResult> results = healthCheckManager.getLastCheckResults();
            boolean allHealthy = results.stream().allMatch(HealthCheckResult::isHealthy);
            
            response.put("status", allHealthy ? "UP" : "DOWN");
            response.put("timestamp", System.currentTimeMillis());
            response.put("details", results);
            
            logger.info("获取系统健康详细信息");
        } catch (Exception e) {
            logger.error("获取系统健康详细信息时发生异常", e);
            response.put("status", "UNKNOWN");
            response.put("error", e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 手动触发健康检查
     * @return 最新的健康检查结果
     */
    @GetMapping("/check")
    public Map<String, Object> triggerHealthCheck() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            logger.info("手动触发系统健康检查");
            List<HealthCheckResult> results = healthCheckManager.performHealthChecks();
            boolean allHealthy = results.stream().allMatch(HealthCheckResult::isHealthy);
            
            response.put("status", allHealthy ? "UP" : "DOWN");
            response.put("timestamp", System.currentTimeMillis());
            response.put("details", results);
            
            logger.info("手动健康检查完成，结果: {}", response.get("status"));
        } catch (Exception e) {
            logger.error("执行手动健康检查时发生异常", e);
            response.put("status", "UNKNOWN");
            response.put("error", e.getMessage());
        }
        
        return response;
    }
}